package com.spnice.sgsms.controller;

import com.spnice.sgsms.feign.UserClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@Slf4j
@RefreshScope
public class DeviceController {
    @Autowired
    private LoadBalancerClient loadBalancerClient;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserClient userClient;
    @Value("${my.deviceName}")
    private String info;

    @GetMapping("/info")
    public String info() {
        return info;
    }

    @GetMapping("/deviceInfo")
    public String deviceInfo() {
        RestTemplate restTemplate = new RestTemplate();
        String userName = restTemplate.getForObject(
                "http://localhost:8081/user",
                String.class
        );
        log.info("当前用户名：{}", userName);
        return "调用成功";
    }

    @GetMapping("/deviceInfo2")
    public String deviceInfo2() {
        ServiceInstance user = loadBalancerClient.choose("USER");
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://" + user.getHost() + ":" + user.getPort() + "/user";
        String userName = restTemplate.getForObject(url, String.class);
        log.info("当前用户名：{}", userName);
        return "调用成功2";
    }

    @GetMapping("/deviceInfo3")
    public String deviceInfo3() {
        String userName = restTemplate.getForObject("http://USER/user", String.class);
        log.info("当前用户名：{}", userName);
        return "调用成功3";
    }

    @GetMapping("/deviceInfo4")
    public String deviceInfo4() {
        String userName = userClient.test();
        log.info("当前用户名：{}", userName);
        return "调用成功4";
    }
}
